require 'base/class_loader.rb'

# app 以下のプロジェクトをロードする．
# demoruby 専用ね．
#
# Author:: krdlab
#
class AppLoader
  class Info
    attr_accessor :app_dir, :app_name, :app_klass
  end
  def auto_load(root_dir)
    info = Info.new
    info.app_dir, info.app_name = get_last_app_dir_and_name(root_dir)
    return do_load(info)
  end
  def load(app_dir)
    info = Info.new
    info.app_dir  = app_dir
    info.app_name = File.basename(app_dir)
    return do_load(info)
  end

private
  def do_load(info)
    add_to_load_path(info.app_dir)
    c_dir = File.join(info.app_dir, 'controller')
    info.app_klass = ClassLoader.new(c_dir, [/.+_app.+/]).collect.first
    return [info]
  end
  def get_last_app_dir_and_name(root_dir)
    app_root_dir = root_dir  #File.join(@root_dir, 'app')
    app_dir = nil
    app_name = nil
    Dir.foreach(app_root_dir) {|f|
      path = File.join(app_root_dir, f)
      if f =~ /^[_\-a-zA-Z0-9]+/ && File.directory?(path) then
        app_dir = path
        app_name = f
        break
      end
    }
    return app_dir, app_name
  end
  def add_to_load_path(path)
    return if path.nil? or path.empty?
    $LOAD_PATH.push(path) if not $LOAD_PATH.include?(path)
  end
end

